package com.xoa.global.timedTask;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.timedTask.TimedTaskMapper;
import com.xoa.dao.timedTask.TimedTaskRecordMapper;
import com.xoa.model.certificate.CrmCertificateWithBLOBs;
import com.xoa.model.common.SysCode;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.timedTask.TimedTask;
import com.xoa.model.timedTask.TimedTaskRecord;
import com.xoa.service.certificate.CrmCertificateService;
import com.xoa.service.sms.SmsService;
import com.xoa.util.DateFormat;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.quartz.CronExpUtil;
import com.xoa.util.quartz.QuartzService;
import com.xoa.util.quartz.TaskUtils;
import com.xoa.util.quartz.model.SchedulerJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者 廉立深
 * 日期 2020/8/26
 * 方法介绍  资格证书的定时任务
 **/
@Component
public class CertificateTime {


    @Resource
    private QuartzService quartzService;

    @Resource
    private TimedTaskMapper timedTaskMapper;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private SmsService smsService;

    @Resource
    private CrmCertificateService crmCertificateService;

    /**
     * 作者 廉立深
     * 日期 2020/8/26
     * 方法介绍   将添加的资格证书放入定时容器
     * 参数 []
     * 返回 void
     **/
    public void CerticateTo(CrmCertificateWithBLOBs certificate , String sqlType,boolean isCarried){
        try {
            TimedTask timedTask = timedTaskMapper.selectByPrimaryKey(2);
            timedTask.setTaskName(certificate.getCertId().toString());
            timedTask.setMethodName("CerticateExecute");
            if (isCarried){
                timedTask.setCron(CronExpUtil.getCron(certificate.getRemindTime()));
            }

            SchedulerJob schedulerJob = TaskUtils.copyTimedTaskBean(timedTask,sqlType);
            if(schedulerJob != null){
                //为了在执行日志表里面  有userId
                schedulerJob.setUserId(certificate.getSupplierUser());

                //传递参数
                Map map = new HashMap<>();
                map.put("jobName",schedulerJob.getJobName());
                map.put("jobGroup",schedulerJob.getJobGroup());
                map.put("CertId",certificate.getCertId().toString());
                map.put("CertName",certificate.getCertName());
                map.put("SupplierUser",certificate.getSupplierUser());
                map.put("Remark",certificate.getRemark());
                map.put("sqlType",sqlType);
                schedulerJob.setJobData(new Gson().toJson(map));

                //添加到容器
                quartzService.addTimerJob(schedulerJob);
            }else{
                //任务转换失败设置任务为关闭状态
                //timedTaskMapper.shutDownTimedTask(timedTask.getTaskId());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //添加数据所执行的方法，（执行事务提醒）
    public void CerticateExecute(String jsonStr){
        try {
            Map map = new Gson().fromJson(jsonStr, Map.class);
            String sqlType = (String) map.get("sqlType");
            ContextHolder.setConsumerType("xoa"+sqlType);
            SmsBody smsBody = new SmsBody();
            smsBody.setFromId( (String) map.get("SupplierUser"));
            smsBody.setContent("资格证书管理！主题：" +  (String) map.get("CertName"));
            Date date = new Date();
            long dateLong = date.getTime()/1000;
            String strDate = String.valueOf(dateLong);
            Integer dateInt = Integer.valueOf(strDate.trim());
            smsBody.setSendTime(dateInt);
            smsBody.setIsAttach("0"); //无附件
            smsBody.setRemindUrl("/supplier/newAdd?isEdit=false&certId=" + (String) map.get("CertId") );

            SysCode sysCode = new SysCode();
            sysCode.setCodeName("资格证书管理");
            sysCode.setParentNo("SMS_REMIND");
            SysCode codeNoByNameAndParentNo = sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
            if (codeNoByNameAndParentNo != null) {
                smsBody.setSmsType(codeNoByNameAndParentNo.getCodeNo());
            }
            String title = (String) map.get("SupplierUser") + "：有提醒！";
            String context = "主题:" + (String) map.get("Remark");
            smsService.saveSms(smsBody,(String) map.get("SupplierUser") , "1", "1", title, context, sqlType);

            //删除任务（已经提醒过）
            SchedulerJob schedulerJob = new SchedulerJob();
            schedulerJob.setJobName( (String) map.get("jobName") );
            schedulerJob.setJobGroup( (String) map.get("jobGroup") );
            quartzService.deleteTimerJob( schedulerJob );
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //启动项目所执行的方法
    public void CerticateStartExecute(String sqlType){
        try {
            Map map = new HashMap();
            map.put("remindTime", DateFormat.getStrDate(new Date()));
            List<CrmCertificateWithBLOBs> crmCertificateWithBLOBs = crmCertificateService.selectByCertificates(map);
            for (CrmCertificateWithBLOBs certificate : crmCertificateWithBLOBs) {
                CerticateTo(certificate,sqlType,true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
